package com.lottery.controller.pc28.lobbyController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.dto.BetInfoDto;
import com.lottery.service.pc28.lobbyService.*;
import com.lottery.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/api/hall")
public class HallController {
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private BarrageService barrageService;
	@Autowired
	private BetNoticeService betNoticeService;
	@Autowired
	private RuleService ruleService;
	@Resource
	private AccostService accostService;
	@Resource
	private BannedWordsService bannedWordsService;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.lottery.controller.lobbyController.zxtrchy#getNotice(javax.servlet.
	 * http. HttpServletRequest)
	 */
	@CrossOrigin
	@RequestMapping(value = "/notice", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String getNotice(HttpServletRequest request) {
		JSONObject jObject = new JSONObject();
		String body = "";
		try {
			body = readHttpBody(request);
			JSONObject obj = JSONObject.parseObject(body);
			logger.debug("notice****************************:{}", body);
			int userId = obj.getInteger("userId");
			// int lotteyType = obj.getInteger("lotteyType");
			return noticeService.queryNotice(userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("*****getNotice error******:", e);
			jObject.put("result", "1");
			jObject.put("msg", "失败");
		}

		return jObject.toJSONString();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.lottery.controller.lobbyController.zxtrchy#getAppNotice(javax.
	 * servlet. http.HttpServletRequest)
	 */
	@CrossOrigin
	@RequestMapping(value = "/public/appNotice", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String getAppNotice(HttpServletRequest request) {
		JSONObject jObject = new JSONObject();
		String body = "";
		try {
			body = readHttpBody(request);
			JSONObject obj = JSONObject.parseObject(body);
			logger.debug("***********getAppNotice in*****************:{}", body);
			// int lotteyType = obj.getInteger("lotteyType");
			String ret = noticeService.getAppNotice();
			logger.debug("***********getAppNotice out*****************:{}", ret);
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("*****getNotice error******:", e);
			jObject.put("result", "1");
			jObject.put("msg", "失败");
		}

		return jObject.toJSONString();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.lottery.controller.lobbyController.zxtrchy#getBarrage(javax.servlet.
	 * http. HttpServletRequest)
	 */

	@CrossOrigin
	@RequestMapping(value = "/public/barrage", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String getBarrage(HttpServletRequest request) {
		JSONObject jObject = new JSONObject();
		String body = "";
		try {
			body = readHttpBody(request);
			logger.debug("barrage in:{}", body);
			JSONObject obj = JSONObject.parseObject(body);

			int index = obj.getInteger("index");
			int lotteyType = obj.getInteger("lotteyType");
			return barrageService.queryBarrage(index, lotteyType);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("*****getBarrage error******:", e);
			jObject.put("result", "1");
			jObject.put("msg", "失败");
		}

		return jObject.toJSONString();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.lottery.controller.lobbyController.zxtrchy#getbetNotice(javax.
	 * servlet. http.HttpServletRequest)
	 */

	@CrossOrigin
	@RequestMapping(value = "/public/bet", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String getbetNotice(HttpServletRequest request) {
		JSONObject jObject = new JSONObject();
		String body = "";
		try {
			body = readHttpBody(request);
			logger.info("bet index={}", body);
			JSONObject obj = JSONObject.parseObject(body);

			int lotteyType = obj.getInteger("lotteyType");
			int index = obj.getInteger("index");
			String agencyId = obj.getString("agencyId");
			String queryBetNotice = betNoticeService.queryBetNotice(index, lotteyType,agencyId);
			logger.info("bet return={}", queryBetNotice);
			return queryBetNotice;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("*****getbetNotice error******:", e);
			jObject.put("result", "1");
			jObject.put("msg", "失败");
		}

		return jObject.toJSONString();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.lottery.controller.lobbyController.zxtrchy#getAccost(javax.servlet.
	 * http. HttpServletRequest)
	 */

	@CrossOrigin
	@RequestMapping(value = "/personalChat", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String getAccost(HttpServletRequest request) {
		JSONObject jObject = new JSONObject();
		String body = "";
		try {
			body = readHttpBody(request);
			JSONObject obj = JSONObject.parseObject(body);

			int userId = obj.getInteger("userId");
			return accostService.getAccost(userId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("*****getAccost error******:", e);
			jObject.put("result", "1");
			jObject.put("msg", "失败");
		}
		return jObject.toJSONString();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.lottery.controller.lobbyController.zxtrchy#playWay(javax.servlet.
	 * http. HttpServletRequest)
	 */

	@CrossOrigin
	@RequestMapping(value = "/playWay", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String playWay(HttpServletRequest request) {
		JSONObject jObject = new JSONObject();
		String body = "";
		try {
			body = readHttpBody(request);

			JSONObject obj = JSONObject.parseObject(body);

			int userId = obj.getInteger("userId");

			int receiveId = obj.getInteger("receiveId");

			Integer type = obj.getInteger("type");

			/*
			 * List<BetInfoDto> param = (List<BetInfoDto>)
			 * obj.getJSONObject("param");
			 */

			int lotteyType = obj.getInteger("lotteyType");

			int loginType = obj.getInteger("loginType") == null ? 0 : obj.getInteger("loginType");

			logger.debug("下注的信息={}", userId, body);

			// Boolean vague = IndistinctCheckUtils.vague(param);
			// 校验敏感词汇
			/*
			 * boolean checkParam = bannedWordsService.checkParam(param); if
			 * (!checkParam) { jObject.put("result", "0"); jObject.put("msg",
			 * "请不要输入敏感词汇!"); return jObject.toJSONString(); }
			 */

			if (type != null) {
				if (type == 2) {
					List<BetInfoDto> param = JSON.parseArray(obj.getString("param"), BetInfoDto.class);
					String playWay = null;
					if (lotteyType == 1) {
						// String param = obj.getString("param");
						if (loginType == 1) {
							playWay = ruleService.sscTourPlayWay(param, userId, lotteyType);
						} else {
							playWay = ruleService.sscPlayWay(param, userId, lotteyType);
						}
					} else {

						if (loginType == 1) {
							playWay = ruleService.pc28TourPlayWay(param, userId, lotteyType);
						} else {
							playWay = ruleService.pc28PlayWay(param, userId, lotteyType);
						}

					}
					return playWay;
				} else {
					if (loginType != 1) {
						String param = obj.getString("param");
						// 校验敏感词汇
						boolean checkParam = bannedWordsService.checkParam(param);
						if (!checkParam) {
							jObject.put("result", "1");
							jObject.put("msg", "请不要输入敏感词汇!");
							return jObject.toJSONString();
						}
						if (type == 1) {
							String insertBarrage = barrageService.insertBarrage(userId, param, lotteyType);
							return insertBarrage;
						} else if (type == 3) {
							String setAccost = accostService.setAccost(userId, receiveId, param);
							return setAccost;
						}
					} else {
						jObject.put("result", "1");
						jObject.put("msg", "游客不能发送弹幕,请登入!");
						return jObject.toJSONString();
					}

				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("*****playWay error******:", e);
			e.printStackTrace();
			jObject.put("result", "1");
			jObject.put("msg", "网络错误!");
		}

		return jObject.toJSONString();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.lottery.controller.lobbyController.zxtrchy#getImportantNotice(javax.
	 * servlet.http.HttpServletRequest)
	 */

	@CrossOrigin
	@RequestMapping(value = "/importantNotice", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public String getImportantNotice(HttpServletRequest request) {

		String body = "";
		try {
			body = readHttpBody(request);
		} catch (Exception e) {
			logger.error("*****getImportantNotice error******:", e);
			e.printStackTrace();
		}

		JSONObject obj = JSONObject.parseObject(body);

		int id = obj.getInteger("id");

		String queryNotice = noticeService.queryImportantNotice(id);
		logger.info("公告返回的信息={}", queryNotice);
		return queryNotice;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.lottery.controller.lobbyController.zxtrchy#interceptorRedirect()
	 */

	@CrossOrigin
	@RequestMapping(value = "/public/interceptor", produces = "application/json;charset=utf-8")
	@ResponseBody
	public String interceptorRedirect() {
		JSONObject jObject = new JSONObject();
		jObject.put("result", "1");
		jObject.put("msg", "权限不足");
		return jObject.toJSONString();
	}

	/**
	 * 解析json
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	private String readHttpBody(HttpServletRequest request) throws Exception {

		// 读取input流
		/*
		 * BufferedReader br = new BufferedReader( new
		 * InputStreamReader((ServletInputStream) request.getInputStream(),
		 * "utf-8")); StringBuffer sb = new StringBuffer(""); String temp; while
		 * ((temp = br.readLine()) != null) { sb.append(temp); } br.close();
		 * return sb.toString();
		 */
		String attribute = (String) request.getAttribute("json");
		return attribute;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.lottery.controller.lobbyController.zxtrchy#weixinRequest(javax.
	 * servlet. http.HttpServletRequest)
	 */

	@CrossOrigin
	@RequestMapping(value = "/weixinRequest", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> weixinRequest(HttpServletRequest request) {
		String body = null;
		Map<String, Object> map = new HashMap<>();
		try {
			body = readHttpBody(request);
			JSONObject obj = JSONObject.parseObject(body);
			String secret = obj.getString("secret");
			String URL = obj.getString("URL");
			String appid = obj.getString("appid");
			// 获取token
			String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid
					+ "&secret=" + secret;
			String params = "access_token";
			String reString = JsonUtils.getExpectArrays(url, params);
			// 根据token获取 ticket
			String urlToken = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + reString
					+ "&type=jsapi";
			String jsapi_ticket = JsonUtils.getExpectArrays(urlToken, "ticket");
			map.put("jsapi_ticket", jsapi_ticket);
			// 3、时间戳和随机字符串
			String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
			map.put("noncestr", noncestr);
			// 时间戳
			String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
			map.put("timestamp", timestamp);
			// 用时间戳、随机数、jsapi_ticket和要访问的url按照签名算法拼接字符串；
			// 5、将参数排序并拼接字符串
			String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url="
					+ URL;
			// 对第三步的字符串进行SHA1加密，得到签名。
			// 6、将字符串进行sha1加密
			String signature = SHA1(str);
			map.put("signature", signature);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("*****weixinRequest error******:", e);
			e.printStackTrace();
		}
		return map;
	}

	private String SHA1(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
			mdTemp.update(str.getBytes("UTF-8"));

			byte[] md = mdTemp.digest();
			int j = md.length;
			char buf[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
				buf[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(buf);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("*****SHA1 error******:", e);
			return null;
		}
	}
}
